<?php
/*
 * Created on
 * Date: Apr 20, 2008
 * Author: William Yang
 */
require_once(dirname(__FILE__)."/constants.php");
require_once(TRANSACTIONS_DIR_PATH."/usermanager.php");

class FileUploader {
	private $file_max_size;
	private $dest_file_name;
	private $user_uid;
	
	const SAVE_FILE_FAILED  = -1;
	
	public function __construct ($file_max_size, $dest_file_name, $user_uid) {
		$this->file_max_size = $file_max_size;
		$this->dest_file_name = str_replace("\\", "/", $dest_file_name);
		$this->user_uid = $user_uid;
	}
	
	public function _do($FILE_PARAMS) {

		$f_name		= $FILE_PARAMS['name'];
		$f_tmp_name	= $FILE_PARAMS['tmp_name'];
		$f_size		= $FILE_PARAMS['size'];
		$f_error	= $FILE_PARAMS['error'];
		
		if ($f_error == UPLOAD_ERR_INI_SIZE ||
			$f_error == UPLOAD_ERR_FORM_SIZE ||
			$f_error == UPLOAD_ERR_PARTIAL ||
			$f_error == UPLOAD_ERR_NO_FILE) {
			return $f_error;
		} else if ($f_size > $this->file_max_size)
			return UPLOAD_ERR_FORM_SIZE;
		else if ($f_error == UPLOAD_ERR_OK) {
			// Clean up the old icon first.
			$this->cleanup();
			
			$stat = move_uploaded_file($f_tmp_name, $this->dest_file_name);
			
			// Update database.
			// trim off the directory part of the path
			$slash_pos = strrpos($this->dest_file_name, "/");
			$file_name = substr($this->dest_file_name, $slash_pos + 1);
			
			$u_mgr				= new UserManager();
			$u_mgr->uid			= $this->user_uid;
			$u_mgr->icon_file	= $file_name;
			
			$u_mgr->update_info();
			
			return ($stat == TRUE ? $f_error : FileUploader::SAVE_FILE_FAILED);
		}
	}
	
	private function cleanup() {
		$icon_file = UserManager::GetIconByUID($this->user_uid);
		if ($icon_file == null)
			return;
		
		// trim off the directory part of the path
		@unlink(RESOURCES_DIR_PATH.$icon_file);
	}
}
?>
